// 引入cookie
import { ElckerCookie, ElckerTokenKey } from '~/utils/cookie';
//引入对应的API
import ElckerAuthApi from '@/api/elcker/ElckerAuthApi';
//定义状态值
const state = {
  userInfo: ElckerCookie.get(ElckerTokenKey.userInfoKey)
    ? JSON.parse(ElckerCookie.get(ElckerTokenKey.userInfoKey))
    : null, // 用户信息对象
  accessToken: ElckerCookie.get(ElckerTokenKey.accessTokenKey), // 访问令牌字符串
  refreshToken: ElckerCookie.get(ElckerTokenKey.refreshTokenKey), // 刷新令牌字符串
  isLogin: ElckerCookie.get(ElckerTokenKey.isCome) ? JSON.parse(ElckerCookie.get(ElckerTokenKey.isCome)) : false,
};
// 获取用户数据
const getters = {
  getUser(state: any) {
    return state.userInfo;
  },
  getToken(state: any) {
    return state.accessToken;
  },
  isLogin(state: any) {
    return state.isLogin;
  },
  refreshToken(state: any) {
    return state.refreshToken;
  },
  getElckerState(state: any) {
    return state;
  },
};
// 改变状态值的set 方法
const mutations = {
  // 赋值用户状态
  SET_USER_STATE(state: any, data: any) {
    // 状态赋值
    const { userInfo, access_token, refresh_token } = data;
    state.userInfo = userInfo;
    state.accessToken = access_token;
    state.refreshToken = refresh_token;
    state.isLogin = true;
    // 保存到cookie中
    ElckerCookie.set(ElckerTokenKey.userInfoKey, userInfo);
    ElckerCookie.set(ElckerTokenKey.accessTokenKey, access_token);
    ElckerCookie.set(ElckerTokenKey.refreshTokenKey, refresh_token);
    ElckerCookie.set(ElckerTokenKey.isCome, 'true');
  },
  // 重置用户状态,退出和登录失败时用
  RESET_USER_STATE(state: any) {
    // 状态置空
    state.userInfo = null;
    state.accessToken = null;
    state.refreshToken = null;
    state.isLogin = false;
    // 移除cookie中的数据
    ElckerCookie.remove(ElckerTokenKey.userInfoKey);
    ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
    ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
    ElckerCookie.remove(ElckerTokenKey.isCome);
  },
};

// 定义行为 方法
const actions = {
  // 退出
  // 登录操作
  UserLogin({ commit }: any, userData: any) {
    const { username, password } = userData;
    return new Promise((resolve, reject) => {
      ElckerAuthApi.userLogin({ username: username.trim(), password: password })
        .then((response: any) => {
          commit('SET_USER_STATE', response);
          resolve(response); // 正常响应钩子
        })
        .catch((error: any) => {
          // 重置状态
          commit('RESET_USER_STATE');
          reject(error); // 异常
        });
    });
  },

  // 退出
  UserLogout({ state, commit }: any, redirectURL: string) {
    // 调用退出接口, 上面不要忘记导入 logout 方法
    ElckerAuthApi.userLoginOut(state.accessToken)
      .then(() => {
        // 重置状态
        commit('RESET_USER_STATE');
        // 重写向回来源地址，如果没有传重定向地址则回到到登录页
        window.location.href = (redirectURL || process.env.VUE_APP_PAGE_LOGIN) + '';
      })
      .catch(() => {
        // 重置状态
        commit('RESET_USER_STATE');
        window.location.href = (redirectURL || process.env.VUE_APP_PAGE_LOGIN) + '';
      });
  },

  // 发送刷新令牌
  SendRefreshToken({ state, commit }: any) {
    return new Promise((resolve, reject) => {
      // 判断是否有刷新令牌
      if (!state.refreshToken) {
        commit('RESET_USER_STATE');
        reject('没有刷新令牌');
        return;
      }
      // 发送请求
      ElckerAuthApi.refreshToken(state.refreshToken)
        .then((response: any) => {
          // 更新用户状态新数据
          commit('SET_USER_STATE', response);
          resolve(response); // 正常钩子
        })
        .catch((error: any) => {
          // 重置状态
          commit('RESET_USER_STATE');
          reject(error);
        });
    });
  },
};

export default {
  state,
  mutations,
  actions,
  getters,
};
